import 'package:azring/entity/food_record.dart';
import 'package:azring/pages/status/activity/routes.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:azring/pages/sleep/sleep_page.dart';
import 'package:azring/pages/insights/InsightsView.dart';
import 'package:azring/pages/action/actionView.dart';
import 'package:azring/pages/profile/ProfileView.dart';
import 'status_logic.dart';
import 'status_state.dart';
import '../../core/controllers/ring_controller.dart';
import '../../routes/app_routes.dart';
import '../../gen/assets.gen.dart';
import '../../common/styles/theme_manager.dart';
import '../../widgets/health_dashboard.dart';
import '../../widgets/health_metric_card.dart';
import '../../widgets/pressure_chart.dart';
import '../../widgets/health_score_explanation_page.dart';
import '../../core/controllers/mood_emoji_controller.dart';
import '../../common/widgets/sync_progress_indicator.dart';
import 'routes.dart';
import 'calendar/routes.dart';
import 'diet_record/routes.dart';
import 'pressure/routes.dart';
import 'daily_events/event_summary/routes.dart';
import 'daily_events/routes.dart';
import 'heart_rate/routes.dart';
import 'blood_oxygen/routes.dart';
import 'exercise/routes.dart';
import 'menstrual_cycle/routes.dart';

/// 状态页面
class StatusView extends GetView<StatusLogic> {
  const StatusView({super.key});

  // 获取戒指控制器
  RingController get ringLogic => Get.find<RingController>();

  /// 便捷引用
  RxInt get selectedMoodIndex => controller.state.selectedMoodIndex;
  RxBool get hasMoodRecorded => controller.state.hasMoodRecorded;

  /// 页面列表
  List<Widget> _getPages() {
    return [
      _buildStatusContent(), // 状态页内容
      const SleepView(),
      const InsightsView(),
      const ActionView(),
      const ProfileView(),
    ];
  }

  /// 显示异常值列表弹窗
  void _showAbnormalValuesDialog(List<String> abnormalValues) {
    Get.dialog(
      Center(
        child: Container(
          width: 320.w,
          constraints: BoxConstraints(
            maxHeight: 500.h,
          ),
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: const Color(0xFF121212),
            border: Border.all(width: 1.w, color: const Color(0xff50555C)),
            borderRadius: BorderRadius.circular(24.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 标题和关闭按钮
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '异常体征详情',
                    style: TextStyle(
                      fontSize: 18.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  GestureDetector(
                    onTap: () => Get.back(),
                    child: Container(
                      width: 25.w,
                      height: 25.h,
                      decoration: BoxDecoration(
                        color: Colors.grey[700],
                        shape: BoxShape.circle,
                      ),
                      child: const Icon(
                        Icons.close,
                        color: Colors.white,
                        size: 18.0,
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 20.h),

              // 异常值列表
              Flexible(
                child: ListView.separated(
                  shrinkWrap: true,
                  itemCount: abnormalValues.length,
                  separatorBuilder: (context, index) => SizedBox(height: 12.h),
                  itemBuilder: (context, index) {
                    return Container(
                      width: double.infinity,
                      padding: EdgeInsets.all(16.w),
                      decoration: BoxDecoration(
                        color: const Color(0xFF282528),
                        borderRadius: BorderRadius.circular(12.r),
                        border: Border.all(
                          color: const Color(0xFF343231),
                          width: 1.0,
                        ),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 序号
                          Container(
                            width: 24.w,
                            height: 24.w,
                            decoration: BoxDecoration(
                              color: const Color(0xFFED5C2F).withOpacity(0.2),
                              shape: BoxShape.circle,
                            ),
                            child: Center(
                              child: Text(
                                '${index + 1}',
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  color: const Color(0xFFED5C2F),
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                          SizedBox(width: 12.w),
                          // 异常值文本
                          Expanded(
                            child: Text(
                              abnormalValues[index],
                              style: TextStyle(
                                fontSize: 14.sp,
                                color: const Color(0xFFDEDEDE),
                                height: 1.5,
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
      barrierColor: Colors.black54,
    );
  }

  /// 弹出添加饮食记录选项（中心弹窗）
  void _showDietAddDialog() {
    // 获取当前时间并自动填充
    final now = DateTime.now();
    // 如果有API数据，使用第一个选项作为默认值，否则使用时间判断
    final defaultMealTimeLabel = controller.state.mealTypeList.isNotEmpty
        ? controller.state.mealTypeList.first.label
        : _getMealTimeByHour(now.hour);
    final defaultMealTimeValue = controller.state.mealTypeList.isNotEmpty
        ? controller.state.mealTypeList.first.value
        : "1"; // 默认值
    final selectedMealTimeLabel = RxString(defaultMealTimeLabel);
    final selectedMealTimeValue = RxString(defaultMealTimeValue);
    final mealTimeExpanded = RxBool(false);

    Get.dialog(
      Center(
        child: SingleChildScrollView(
          child: Container(
            width: 320.0,
            padding: const EdgeInsets.all(20.0),
            decoration: BoxDecoration(
              color: const Color(0xFF121212),
              border: Border.all(width: 1.w, color: const Color(0xff50555C)),
              borderRadius: BorderRadius.circular(24.r),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 关闭按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () => Get.back(),
                      child: Container(
                        width: 25.w,
                        height: 25.h,
                        decoration: BoxDecoration(
                          color: Colors.grey[700],
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.close,
                          color: Colors.white,
                          size: 18.0,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16.0),

                // 操作按钮
                _buildActionItem('拍照上传', Icons.camera_alt, () async {
                  Get.back();
                  await controller.pickAndUploadImage(
                    isCamera: true,
                    mealType: selectedMealTimeValue.value,
                  );
                }),
                const SizedBox(height: 12.0),
                _buildActionItem('相册上传', Icons.photo_library, () async {
                  Get.back();
                  await controller.pickAndUploadImage(
                    isCamera: false,
                    mealType: selectedMealTimeValue.value,
                  );
                }),
                const SizedBox(height: 12.0),
                _buildActionItem('文字记录', Icons.text_fields, () async {
                  Get.back(); // 关闭当前弹窗
                  // 跳转到文字记录页面，传递用餐时段和日期
                  final result = await Get.toNamed(
                    StatusRoutes.textRecord,
                    arguments: {
                      'mealTime': selectedMealTimeValue.value,
                    },
                  );
                  // 如果保存成功，刷新饮食记录列表
                  if (result == true) {
                    controller.refreshFoodRecords();
                  }
                }),

                const SizedBox(height: 24.0),
                // 用餐时段
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Text(
                      '用餐时段',
                      style: TextStyle(
                        fontSize: 14.0,
                        color: Colors.white,
                      ),
                    ),
                    const SizedBox(height: 12.0),
                    _buildMealTimeDropdown(selectedMealTimeLabel, selectedMealTimeValue, mealTimeExpanded),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
      barrierColor: Colors.black54,
    );
  }

  Widget _buildActionItem(String label, IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        height: 56.0,
        padding: const EdgeInsets.symmetric(horizontal: 20.0),
        decoration: BoxDecoration(
          color: const Color(0xFF282528),
          borderRadius: BorderRadius.circular(36.r),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: Colors.white, size: 22.0),
            const SizedBox(width: 12.0),
            Text(
              label,
              style: const TextStyle(fontSize: 16.0, color: Colors.white),
            ),
          ],
        ),
      ),
    );
  }

  /// 根据小时数自动判断用餐时段
  String _getMealTimeByHour(int hour) {
    if (hour >= 6 && hour < 11) {
      return '早餐';
    } else if (hour >= 11 && hour < 18) {
      return '午餐';
    } else if (hour >= 18 && hour < 22) {
      return '晚餐';
    } else if (hour >= 22) {
      return '宵夜';
    } else {
      return '其他';
    }
  }

  /// 格式化日期显示（选择后显示年月日）
  String _formatDate(DateTime date) {
    return '${date.year.toString().substring(2)}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  /// 构建用餐时段下拉框
  Widget _buildMealTimeDropdown(RxString selectedMealTimeLabel, RxString selectedMealTimeValue, RxBool isExpanded) {
    return Obx(() {
      // 从controller获取用餐类型列表
      final mealTypes = controller.state.mealTypeList;

      // 如果数据还在加载中，显示默认选项
      if (mealTypes.isEmpty) {
        return Container(
          width: 312.w,
          height: 46.h,
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          decoration: BoxDecoration(
            color: const Color(0xFF2A2A2A),
            borderRadius: BorderRadius.circular(999.0),
            border: Border.all(
              color: const Color(0xFFe7e7e7),
              width: 1.0,
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                selectedMealTimeLabel.value,
                style: const TextStyle(
                  fontSize: 14.0,
                  color: Colors.white,
                ),
              ),
              const Icon(
                Icons.keyboard_arrow_down,
                color: Colors.white,
                size: 20.0,
              ),
            ],
          ),
        );
      }

      return Column(
        children: [
          // 主选择框
          GestureDetector(
            onTap: () => isExpanded.value = !isExpanded.value,
            child: Container(
              width: 312.w,
              height: 46.h,
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              decoration: BoxDecoration(
                color: const Color(0xFF2A2A2A),
                borderRadius: isExpanded.value
                    ? const BorderRadius.only(
                        topLeft: Radius.circular(22.0),
                        topRight: Radius.circular(22.0),
                      )
                    : BorderRadius.circular(999.0),
                border: Border.all(
                  color: const Color(0xFFe7e7e7),
                  width: 1.0,
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    selectedMealTimeLabel.value,
                    style: const TextStyle(
                      fontSize: 14.0,
                      color: Colors.white,
                    ),
                  ),
                  Icon(
                    isExpanded.value
                        ? Icons.keyboard_arrow_up
                        : Icons.keyboard_arrow_down,
                    color: Colors.white,
                    size: 20.0,
                  ),
                ],
              ),
            ),
          ),
          // 下拉选项 - 向上移动2像素
          isExpanded.value
              ? Transform.translate(
                  offset: const Offset(0, -2),
                  child: Container(
                    width: 314.w,
                    height: 3 * 46.0, // 固定显示3个选项的高度
                    decoration: BoxDecoration(
                      color: const Color(0xFF2A2A2A),
                      borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(24.0),
                        bottomRight: Radius.circular(24.0),
                      ),
                      border: Border.all(
                        color: const Color(0xFF404040),
                        width: 1.0,
                      ),
                    ),
                    child: ListView.builder(
                      padding: EdgeInsets.zero,
                      itemCount: mealTypes.length,
                      itemBuilder: (context, index) {
                        final mealType = mealTypes[index];
                        final isSelected =
                            mealType.label == selectedMealTimeLabel.value;
                        return GestureDetector(
                          onTap: () {
                            selectedMealTimeLabel.value = mealType.label;
                            selectedMealTimeValue.value = mealType.value;
                            isExpanded.value = false;
                          },
                          child: Container(
                            width: double.infinity,
                            height: 48.0,
                            padding:
                                const EdgeInsets.symmetric(horizontal: 16.0),
                            decoration: BoxDecoration(
                              borderRadius: index == mealTypes.length - 1
                                  ? const BorderRadius.only(
                                      bottomLeft: Radius.circular(24.0),
                                      bottomRight: Radius.circular(24.0),
                                    )
                                  : BorderRadius.zero,
                            ),
                            child: Align(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                mealType.label,
                                style: TextStyle(
                                  fontSize: isSelected ? 20.sp : 16.sp,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                )
              : const SizedBox.shrink(),
        ],
      );
    });
  }

  Widget _buildStatusContent() {
    return Scaffold(
      body: Obx(() => Stack(
            children: [
              // 主内容区域
              Container(
                child: SafeArea(
                  child: SingleChildScrollView(
                    controller: controller.scrollController,
                    child: Stack(
                      children: [
                        Positioned(
                          top: 0,
                          left: 0,
                          right: 0,
                          height: 200.h,
                          child: Container(
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                begin: Alignment.topRight,
                                end: Alignment.bottomRight,
                                colors: ThemeManager.to.backgroundGradientColors,
                                stops: const [0.1, 0.3, 0.7, 1.0],
                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.all(10.w),
                          child: Column(
                            children: [
                              // 固定顶部区域
                              _buildFixedTopSection(),
                              SizedBox(height: 20.h),

                              // 固定模块（始终显示，不受API控制）
                              ..._buildFixedModules(),

                              // 卡片数据模块（根据API配置动态渲染）
                              _buildCardDataModuleFromAPI(),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          )),
    );
  }

  /// 构建固定的顶部区域（不受API控制）
  /// 只包含标题行和周历
  Widget _buildFixedTopSection() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(7.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题和日历图标
          Row(
            children: [
              Expanded(
                child: Obx(() => Text(
                      '身体状况',
                      style: TextStyle(
                        fontSize: 26.sp,
                        color: ThemeManager.to.primaryTextColor,
                      ),
                    )),
              ),
              // 日历图标
              GestureDetector(
                onTap: () {
                  Get.toNamed(CalendarRoutes.calendar);
                },
                child: Obx(() => Assets.status.calendar.image(
                      width: 24.w,
                      height: 24.w,
                      color: ThemeManager.to.secondaryTextColor,
                    )),
              ),
            ],
          ),
          SizedBox(height: 19.h),

          // 周历显示
          _buildWeeklyCalendar(),
          
          SizedBox(height: 16.h),
          
          // 身体活力评分说明按钮
          Align(
            alignment: Alignment.centerRight,
            child: GestureDetector(
              onTap: () {
                Get.to(() => const HealthScoreExplanationPage());
              },
              child: Icon(
                      Icons.help_outline,
                      color: Colors.white.withValues(alpha: 0.8),
                      size: 16.w,
                    ),
                    
                 
              
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Obx(() => IndexedStack(
            index: controller.state.currentIndex.value,
            children: _getPages(),
          )),
      bottomNavigationBar: Obx(() => Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 数据同步进度指示器
              const SyncProgressIndicator(),
              // 底部导航栏
              Container(
                decoration: const BoxDecoration(
                  border: Border(
                    top: BorderSide(
                      color: Color.fromRGBO(31, 31, 31, 1),
                      width: 1.0,
                    ),
                  ),
                ),
                child: BottomNavigationBar(
                  currentIndex: controller.state.currentIndex.value,
                  onTap: controller.changeTabIndex,
                  type: BottomNavigationBarType.fixed,
                  selectedItemColor: const Color(0xffED5C2F),
                  unselectedItemColor:
                      ThemeManager.to.navigationBarUnselectedColor,
                  backgroundColor: ThemeManager.to.navigationBarBackgroundColor,
                  elevation: 0,
                  items: controller.state.bottomNavItems,
                ),
              ),
            ],
          )),
    );
  }

  /// 构建周历显示
  Widget _buildWeeklyCalendar() {
    final now = DateTime.now();
    final weekDays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

    return Obx(() => Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: List.generate(7, (index) {
            final date = now.subtract(Duration(days: 6 - index));
            final isSelected =
                controller.state.selectedDate.value.day == date.day;

            // 格式化日期为 "YYYY-MM-DD" 以匹配 API 数据
            final dateStr =
                '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
            final statusScore = controller.state.statusScoreMap[dateStr];

            return GestureDetector(
              onTap: () {
                controller.state.selectedDate.value = date;
              },
              child: Container(
                width: 46.w,
                height: 64.w,
                decoration: BoxDecoration(
                  color: isSelected
                      ? ThemeManager.to.activeColor.withOpacity(0.3) // 橙色透明背景
                      : Colors.black.withOpacity(0.3), // 黑色透明背景
                  border: isSelected
                      ? Border.all(
                          color: ThemeManager.to.activeColor,
                          width: 1.0,
                        )
                      : null,
                  borderRadius: BorderRadius.circular(97.r),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      weekDays[index],
                      style: TextStyle(
                        fontSize: 11.sp,
                        fontWeight: FontWeight.w300,
                        color: ThemeManager.to.secondaryTextColor,
                      ),
                    ),
                    SizedBox(height: 1.h),
                    Text(
                      date.day.toString().padLeft(2, '0'),
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w500,
                        color: ThemeManager.to.secondaryTextColor,
                      ),
                    ),
                    SizedBox(height: 1.h),
                    // 激活状态图标和分数
                    if (isSelected) ...[
                      Assets.status.calendarActive
                          .image(width: 16.w, height: 8.h),
                    ] else ...[
                      Text(
                        statusScore != null ? '$statusScore分' : '--分',
                        style: TextStyle(
                          fontSize: 10.sp,
                          color: const Color(0xff3CE89B),
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            );
          }),
        ));
  }

  /// 构建卡片数据模块（根据API配置动态渲染内部卡片）
  Widget _buildCardDataModule() {
    // 获取所有卡片类型的模块
    final cardModules = ['心率', '心率变异性', '睡眠', '血氧饱和度', '活动', '锻炼记录', '生理周期'];

    // 获取显示的卡片模块列表（已按sort排序）
    final displayedCardModules = controller.state.displayedModules
        .where((m) => cardModules.contains(m.moduleName))
        .toList();

    // 如果没有要显示的卡片，返回空
    if (displayedCardModules.isEmpty) {
      return const SizedBox.shrink();
    }

    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题和时间
          Row(
            children: [
              Text(
                '卡片数据',
                style: TextStyle(
                  fontSize: 22.sp,
                  color: ThemeManager.to.secondaryTextColor,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Spacer(),
              Builder(builder: (context) {
                final now = DateTime.now();
                final weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                final weekday = weekdays[now.weekday - 1];
                final timeStr =
                    '${now.year}/${now.month}/${now.day},$weekday,${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
                return Text(
                  timeStr,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[400],
                  ),
                );
              }),
            ],
          ),
          SizedBox(height: 10.h),

          // 动态渲染卡片（每行最多2个）
          Column(
            children: _buildCardRows(displayedCardModules),
          ),

          SizedBox(height: 18.h),
          // 编辑卡片按钮
          GestureDetector(
            onTap: () {
              Get.toNamed(StatusRoutes.editCards);
            },
            child: Container(
              width: double.infinity,
              height: 51.h,
              decoration: BoxDecoration(
                color: const Color(0xFF282528),
                borderRadius: BorderRadius.circular(20.r),
                border: Border.all(
                  color: const Color(0xFF343231),
                  width: 1.0,
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Assets.status.pen.image(
                    width: 18.w,
                    height: 18.w,
                    color: ThemeManager.to.buttonTextColor,
                  ),
                  SizedBox(width: 10.w),
                  Text(
                    '编辑卡片',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: ThemeManager.to.buttonTextColor,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建卡片行（每行最多2个卡片）
  List<Widget> _buildCardRows(List<ModuleLayoutConfig> cardModules) {
    List<Widget> rows = [];

    for (int i = 0; i < cardModules.length; i += 2) {
      final firstCard = cardModules[i];
      final secondCard = i + 1 < cardModules.length ? cardModules[i + 1] : null;

      rows.add(
        Row(
          children: [
            Expanded(child: _buildSingleCard(firstCard.moduleName)),
            if (secondCard != null) ...[
              SizedBox(width: 8.w),
              Expanded(child: _buildSingleCard(secondCard.moduleName)),
            ] else ...[
              SizedBox(width: 8.w),
              const Spacer(),
            ],
          ],
        ),
      );

      // 添加行间距（除了最后一行）
      if (i + 2 < cardModules.length) {
        rows.add(SizedBox(height: 8.h));
      }
    }

    return rows;
  }

  /// 构建单个卡片
  Widget _buildSingleCard(String cardName) {
    switch (cardName) {
      case '心率':
        return Obx(() => _buildHealthDataCard(
              iconImage: Assets.status.hr.image(width: 14.w, height: 14.h),
              title: '心率',
              value: '${controller.state.averageHeartRate.value} bpm',
              hasChart: true,
              chartType: 'heartRate',
              hasLegend: true,
              legendItems: ['白天', '睡眠'],
              legendColors: [const Color(0xFFFF6B6B), const Color(0xFF4A90E2)],
              buttonText: ringLogic.isHeartRateMeasuring ? '停止测量' : '开始测量',
            ));

      case '心率变异性':
        return Obx(() {
          final averageHrv = controller.state.averageHrv.value;
          final hrvValue = '$averageHrv ms';
          return _buildHealthDataCard(
            iconImage: Assets.status.hrv.image(width: 16.w, height: 16.h),
            title: '心率变异性',
            value: hrvValue,
            hasChart: true,
            chartType: 'hrv',
            hasNormalRange: true,
            normalRange: '50-100次',
            buttonText: ringLogic.isHrvMeasuring ? '停止测量' : '开始测量',
          );
        });

      case '睡眠':
        return Obx(() {
          final sleepCardData = controller.state.sleepCardData.value;
          final sleepDuration = sleepCardData?.sleepDuration ??
              ringLogic.sleepData?.sleepDurationDisplay ??
              '--';
          
          // 构建小睡信息
          bool hasNapInfo = false;
          String napInfo = '';
          if (sleepCardData != null &&
              sleepCardData.shortSleepDuration != null &&
              sleepCardData.shortSleepDuration != '0小时0分' &&
              sleepCardData.shortSleepStartTime != null &&
              sleepCardData.shortSleepEndTime != null) {
            hasNapInfo = true;
            napInfo = '小睡:${sleepCardData.shortSleepDuration} ${sleepCardData.shortSleepStartTime}-${sleepCardData.shortSleepEndTime}';
          }
          
          return _buildHealthDataCard(
            iconImage: Assets.status.sleep.image(width: 16.w, height: 16.h),
            title: '睡眠',
            value: sleepDuration,
            hasChart: true,
            chartType: 'sleep',
            hasNapInfo: hasNapInfo,
            napInfo: napInfo,
          );
        });

      case '血氧饱和度':
        return Obx(() {
          final averageBloodOxygen = controller.state.averageBloodOxygen.value;
          final bloodOxygenValue = '$averageBloodOxygen %';
          return _buildHealthDataCard(
            iconImage:
                Assets.status.bloodOxygen.image(width: 15.w, height: 15.h),
            title: '血氧饱和度',
            value: bloodOxygenValue,
            hasChart: true,
            chartType: 'bloodOxygen',
            hasNormalRange: true,
            normalRange: '95-100%',
            buttonText: ringLogic.isBloodOxygenMeasuring ? '停止测量' : '开始测量',
          );
        });

      case '活动':
        return Obx(() {
          final activityData = controller.state.activityData.value;
          return _buildHealthDataCard(
            iconImage: Assets.status.activity.image(width: 14.w, height: 14.h),
            value: '活动',
            hasProgressRings: true,
            progressData: [
              {
                'label': '步数',
                'current': activityData != null
                    ? '${activityData.steps.toInt()}'
                    : '--',
                'target': activityData != null
                    ? '${activityData.goalsSteps.toInt()}'
                    : '--',
                'unit': '步'
              },
              {
                'label': '卡路里',
                'current': activityData != null
                    ? '${activityData.calories.toInt()}'
                    : '--',
                'target': activityData != null
                    ? '${activityData.goalsCalories.toInt()}'
                    : '--',
                'unit': '卡'
              },
              {
                'label': '活动时间',
                'current': activityData != null
                    ? '${activityData.sportTime.toInt()}'
                    : '--',
                'target': activityData != null
                    ? '${activityData.goalsSportTime.toInt()}'
                    : '--',
                'unit': '分钟'
              },
            ],
          );
        });

      case '锻炼记录':
        final exerciseData = controller.state.exerciseRecordData.value;
        return _buildHealthDataCard(
          iconImage: Assets.status.traing.image(width: 14.w, height: 14.h),
          value: '锻炼记录',
          hasExerciseStats: true,
          exerciseStats: [
            {
              'label': '运动总次数',
              'value': exerciseData?.total != null
                  ? '${exerciseData!.total}次'
                  : '--次'
            },
            {
              'label': '运动总时长',
              'value': exerciseData?.exerciseTime != null
                  ? '${exerciseData!.exerciseTime}分钟'
                  : '--分钟'
            },
            {
              'label': '运动总卡路里',
              'value': exerciseData?.exerciseCalorie != null
                  ? '${exerciseData!.exerciseCalorie}千卡'
                  : '--千卡'
            },
          ],
          buttonText: '开始锻炼',
        );

      case '生理周期':
        return _buildHealthDataCard(
          iconImage: Assets.status.cycle.image(width: 14.w, height: 14.h),
          value: '生理周期',
          hasCycleChart: true,
        );

      default:
        return const SizedBox.shrink();
    }
  }

  /// 构建单个健康数据卡片
  Widget _buildHealthDataCard({
    required Image iconImage,
    String? title,
    String? value,
    bool hasChart = false,
    String? chartType,
    bool hasLegend = false,
    List<String>? legendItems,
    List<Color>? legendColors,
    bool hasNormalRange = false,
    String? normalRange,
    bool hasNapInfo = false,
    String? napInfo,
    bool hasProgressRings = false,
    List<Map<String, String>>? progressData,
    bool hasExerciseStats = false,
    List<Map<String, String>>? exerciseStats,
    bool hasCycleChart = false,
    String? buttonText,
  }) {
    final cardTitle = title ?? '$value';
    
    return GestureDetector(
        onTap: () => _handleCardTap(cardTitle),
        behavior: HitTestBehavior.opaque, // 确保整个区域可点击
        child: Container(
          width: 171.w,
          height: 196.h,
          decoration: BoxDecoration(
            color: const Color(0xFF282528),
            border: Border.all(
              color: const Color(0xFF212121),
              width: 1.0,
            ),
            borderRadius: BorderRadius.circular(20.r),
          ),
          padding: EdgeInsets.all(12.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题和图标 - 使用Stack布局，支持右上角内容
              Stack(
                children: [
                  // 主要内容：图标、标题和数值
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 第一行：图标和数值
                      Row(
                        children: [
                          iconImage,
                          SizedBox(width: 7.w),
                          if (value != null) ...[
                            Text(
                              value,
                              style: TextStyle(
                                fontSize: 14.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ],
                      ),
                      SizedBox(height: 1.h),

                      // 第二行：标题 - 统一布局，始终在图标下方
                      if (title != null) ...[
                        Row(
                          children: [
                            SizedBox(width: 20.w), // 与图标对齐
                            Text(
                              title,
                              style: TextStyle(
                                fontSize: 13.sp,
                                color: Colors.grey[400], // 统一使用灰色
                              ),
                            ),
                          ],
                        ),
                      ]
                    ],
                  ),

                  // 右上角：图例或正常范围
                  Positioned(
                    top: 0,
                    right: 0,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        // 图例（心率卡片的白天/睡眠）
                        if (hasLegend &&
                            legendItems != null &&
                            legendColors != null) ...[
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children:
                                List.generate(legendItems.length, (index) {
                              return Padding(
                                padding: EdgeInsets.only(
                                    bottom: index < legendItems.length - 1
                                        ? 2.h
                                        : 0),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Container(
                                      width: 6.w,
                                      height: 6.w,
                                      decoration: BoxDecoration(
                                        color: legendColors[index],
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                    SizedBox(width: 3.w),
                                    Text(
                                      legendItems[index],
                                      style: TextStyle(
                                        fontSize: 9.sp,
                                        color: Colors.grey[400],
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            }),
                          ),
                        ],
                        // 正常范围（心率变异性卡片）
                        if (hasNormalRange && normalRange != null) ...[
                          Text(
                            normalRange,
                            style: TextStyle(
                              fontSize: 9.sp,
                              color: Colors.grey[400],
                            ),
                          ),
                          Text(
                            '正常范围',
                            style: TextStyle(
                              fontSize: 8.sp,
                              color: Colors.grey[500],
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 8.h),

              // 中间内容区域 - 使用Expanded自动填充剩余空间
              Expanded(
                child: Column(
                  children: [
                    // 图表区域
                    if (hasChart) ...[
                      Expanded(
                        child: Container(
                          width: double.infinity,
                          padding: EdgeInsets.all(8.w),
                          child: _buildHealthChart(chartType ?? '',
                              ringLogic.isConnected, controller),
                        ),
                      ),
                    ],

                    // 活动进度环
                    if (hasProgressRings && progressData != null) ...[
                      Expanded(
                        child: _buildActivityCard(),
                      ),
                    ],

                    // 生理周期图表
                    if (hasCycleChart) ...[
                      Expanded(
                        child: _buildMenstrualCycleChartWithLegend(),
                      ),
                    ],

                    // 小睡信息
                    if (hasNapInfo && napInfo != null) ...[
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 4.h),
                        child: Text(
                          napInfo,
                          style: TextStyle(
                            fontSize: 10.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ),
                    ],

                    // 锻炼记录统计
                    if (hasExerciseStats && exerciseStats != null) ...[
                      Expanded(
                        child: _buildExerciseStatsCard(),
                      ),
                    ],
                  ],
                ),
              ),

              // 按钮 - 固定在底部，距离底部9像素
              if (buttonText != null) ...[
                GestureDetector(
                  onTap: () {
                    // 阻止事件冒泡到父级GestureDetector
                    _handleCardButtonTap(cardTitle);
                  },
                  behavior: HitTestBehavior.opaque, // 阻止点击穿透
                  child: Container(
                    width: double.infinity,
                    height: 32.h,
                    decoration: BoxDecoration(
                      color: const Color(0xFFBEBEBE),
                      borderRadius: BorderRadius.circular(21.r),
                    ),
                    child: Center(
                      child: Text(
                        buttonText,
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.black,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ],
          ),
        ));
  }

  /// 构建健康数据汇总卡片内容（不包含外层Container）
  Widget _buildHealthSummaryCardsContent() {
    return Obx(() {
      final stepsData = ringLogic.stepsData;
      final sleepData = ringLogic.sleepData;
      final heartRateData = ringLogic.heartRateData;
      final bloodOxygenData = ringLogic.bloodOxygenData;
      final hrvData = ringLogic.hrvData;

      return Column(
        children: [
          // 生命关键指标看板标题
          Row(
            children: [
              Assets.status.life.image(
                width: 20.w,
                height: 20.w,
              ),
              SizedBox(width: 9.w),
              Text(
                '生命关键指标看板',
                style: TextStyle(
                  fontSize: 17.sp,
                  color: ThemeManager.to.secondaryTextColor,
                ),
              ),
              const Spacer(),
              GestureDetector(
                onTap: () {},
                child: Assets.status.question.image(
                  width: 18.w,
                  height: 18.w,
                ),
              ),
            ],
          ),
          SizedBox(height: 13.h),

          Container(
            height: 1.0,
            color: const Color(0xFF353235),
          ),
          SizedBox(height: 12.h),

          // 第一行：活动、睡眠
          Obx(() {
            final dashboard = controller.state.dashboardData.value;
            return Row(
              children: [
                Expanded(
                  child: HealthMetricCardBuilder.buildActivityCard(
                    steps: dashboard != null ? '${dashboard.steps}' : '--',
                    target: dashboard != null
                        ? '${dashboard.planStepCount}'
                        : '--',
                    width: 159.w,
                    height: 89.h,
                  ),
                ),
                SizedBox(width: 8.w),
                Expanded(
                  child: HealthMetricCardBuilder.buildSleepCard(
                    minutes: dashboard != null
                        ? '${dashboard.sleepScore}'
                        : (ringLogic.isConnected
                            ? '${(sleepData?.totalSleepTime ?? 0) ~/ 60}'
                            : '--'),
                    quality: dashboard != null
                        ? dashboard.planSleepQuality
                        : (ringLogic.isConnected ? '良' : '--'),
                    width: 159.w,
                    height: 89.h,
                  ),
                ),
              ],
            );
          }),
          SizedBox(height: 10.h),

          Obx(() {
            final dashboard = controller.state.dashboardData.value;
            return HealthMetricCardBuilder.buildCombinedHealthCard(
              heartRate: dashboard != null
                  ? '${dashboard.heartRate}'
                  : (ringLogic.isConnected
                      ? '${heartRateData?.heartRate ?? ringLogic.heartRate}'
                      : '--'),
              heartRateChange: dashboard != null
                  ? dashboard.compareHeartRate
                  :   '--',
              heartRateIncrease: dashboard != null
                  ? dashboard.compareHeartRate.startsWith('+')
                  : true,
              hrv: dashboard != null
                  ? '${dashboard.heartHrv}'
                  :  '--',
              hrvChange: dashboard != null
                  ? dashboard.compareHeartHrv
                  : '--',
              hrvIncrease: dashboard != null
                  ? dashboard.compareHeartHrv.startsWith('+')
                  : false,
              bloodOxygen: dashboard != null
                  ? '${dashboard.bloodOxygen}'
                  : (ringLogic.isConnected
                      ? '${bloodOxygenData?.bloodOxygen ?? '--'}'
                      : '--'),
              width: 342.w,
              height: 89.h,
            );
          }),
          SizedBox(height: 12.h),

          // 异常检测提示
          Obx(() {
            final dashboard = controller.state.dashboardData.value;
            final abnormalValue = dashboard?.abnormalValue ?? '--';
            final abnormalValues = dashboard?.abnormalValues ?? [];

            return GestureDetector(
              onTap: () {
                // 点击时显示异常值列表弹窗
                if (abnormalValues.isNotEmpty) {
                  _showAbnormalValuesDialog(abnormalValues);
                }
              },
              child: Container(
                width: 340.w,
                height: 39.w,
                padding: EdgeInsets.all(12.w),
                decoration: BoxDecoration(
                  color: const Color(0xFF353235),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Row(
                  children: [
                    Stack(
                      clipBehavior: Clip.none,
                      alignment: Alignment.center,
                      children: [
                        Assets.status.danger.image(
                          width: 18.w,
                          height: 18.w,
                        ),
                        Positioned(
                          top: -10.w,
                          child: Assets.status.warnLight.image(
                            width: 45.w,
                            height: 29.w,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(width: 7.w),
                    Expanded(
                      child: RichText(
                        text: TextSpan(
                          children: [
                            TextSpan(
                              text: '检测到 ',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: const Color(0xff908E8D),
                              ),
                            ),
                            TextSpan(
                              text: abnormalValue,
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: const Color(0xFFDEDEDE),
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            TextSpan(
                              text: ' 异常体征数值',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: const Color(0xff908E8D),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      size: 12.sp,
                      color: Colors.grey[400],
                    ),
                  ],
                ),
              ),
            );
          }),
        ],
      );
    });
  }

  /// 构建固定模块列表（不受API控制）
  List<Widget> _buildFixedModules() {
    return [
      // 身体状况图
      Column(
        children: [
          const Center(
            child: HealthDashboard(),
          ),
          SizedBox(height: 20.h),
        ],
      ),

      // 健康计划
      Column(
        children: [
          SizedBox(height: 47.h),
          Obx(() => Row(
                children: [
                  Text(
                    '健康计划',
                    style: TextStyle(
                      fontSize: 22.sp,
                      color: ThemeManager.to.secondaryTextColor,
                    ),
                  ),
                  Spacer(),
                  // 折叠/展开图标
                  GestureDetector(
                    onTap: () {
                      controller.state.isHealthPlanExpanded.value =
                          !controller.state.isHealthPlanExpanded.value;
                    },
                    child: Container(
                      width: 33.w,
                      height: 33.h,
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: const Color(0xFF343231),
                          width: 1.0,
                        ),
                        borderRadius: BorderRadius.circular(16.r),
                      ),
                      child: Center(
                        child: Icon(
                          controller.state.isHealthPlanExpanded.value
                              ? Icons.keyboard_arrow_up
                              : Icons.keyboard_arrow_down,
                          color: ThemeManager.to.buttonTextColor,
                          size: 20.sp,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 8.w),
                  // 自定义按钮
                  GestureDetector(
                    onTap: () => Get.toNamed('/action/create-plan'),
                    child: Container(
                      width: 73.w,
                      height: 33.h,
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: const Color(0xFF343231),
                          width: 1.0,
                        ),
                        borderRadius: BorderRadius.circular(16.r),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Assets.status.pen.image(
                            width: 12.w,
                            height: 12.w,
                            color: ThemeManager.to.buttonTextColor,
                          ),
                          SizedBox(width: 2.w),
                          Text(
                            '自定义',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: ThemeManager.to.buttonTextColor,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              )),
          SizedBox(height: 20.h),
        ],
      ),

      // 可折叠区域：生命关键指标看板 到 今日事件小计（整体背景）
      Obx(() => controller.state.isHealthPlanExpanded.value
          ? Column(
              children: [
                Container(
                  margin: EdgeInsets.all(1.w),
                  padding: EdgeInsets.only(
                    top: 16.h,
                    bottom: 19.h,
                    left: 13.w,
                    right: 13.w,
                  ),
                  decoration: BoxDecoration(
                    color: const Color(0xFF282528),
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Column(
                    children: [
                      // 生命关键指标看板
                      _buildHealthSummaryCardsContent(),
                      SizedBox(height: 34.h),

                      // 饮食记录
                      _buildDietRecordModule(),
                      SizedBox(height: 34.h),

                      // 情绪管理
                      Builder(
                        builder: (context) => _buildMoodManagementModule(context),
                      ),
                      SizedBox(height: 9.83.h),

                      // 压力
                      _buildPressureModule(),
                      SizedBox(height: 34.h),

                      // 今日事件小计
                      _buildTodayEventsSummary(),
                    ],
                  ),
                ),
                SizedBox(height: 20.h),
              ],
            )
          : const SizedBox.shrink()),
    ];
  }

  /// 根据API配置构建卡片数据模块
  Widget _buildCardDataModuleFromAPI() {
    return Obx(() {
      // 获取所有卡片类型的模块
      final cardModules = ['心率', '心率变异性', '睡眠', '血氧饱和度', '活动', '锻炼记录', '生理周期'];

      // 获取显示的卡片模块列表（已按sort排序）
      final displayedCardModules = controller.state.displayedModules
          .where((m) => cardModules.contains(m.moduleName))
          .toList();

      // 如果没有要显示的卡片，返回空
      if (displayedCardModules.isEmpty) {
        return const SizedBox.shrink();
      }

      return Column(
        children: [
          _buildCardDataModule(),
          SizedBox(height: 20.h),
        ],
      );
    });
  }

  /// 构建饮食记录模块
  Widget _buildDietRecordModule() {
    return GestureDetector(
      onTap: () {
        // 跳转到饮食记录详情页
        Get.toNamed(DietRecordRoutes.dietRecord);
      },
      child: Container(
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 饮食记录标题
            Row(
              children: [
                Assets.status.eat.image(
                  width: 20.w,
                  height: 20.w,
                ),
                SizedBox(width: 9.w),
                Text(
                  '饮食记录',
                  style: TextStyle(
                    fontSize: 17.sp,
                    color: ThemeManager.to.secondaryTextColor,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Spacer(),
                GestureDetector(
                  onTap: () {
                    _showDietAddDialog();
                  },
                  child: Container(
                    width: 63.w,
                    height: 27.h,
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: const Color(0xFF343231),
                        width: 1.0,
                      ),
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Assets.status.add.image(
                          width: 8.w,
                          height: 8.w,
                          color: ThemeManager.to.buttonTextColor,
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          '添加',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: ThemeManager.to.buttonTextColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 13.h),
            Container(
              width: double.infinity,
              height: 1.0,
              color: Color(0xFF353235),
            ),
            SizedBox(height: 12.h),
            // 饮食摘要区域
            Row(
              children: [
                // 左侧：卡路里进度圆环
                Expanded(
                  flex: 2,
                  child: Container(
                    height: 120.h,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        // 进度圆环
                        SizedBox(
                          width: 80.w,
                          height: 80.w,
                          child: Obx(() => CircularProgressIndicator(
                                value: controller.state.caloriesProgress,
                                strokeWidth: 6.w,
                                backgroundColor: Colors.grey[800],
                                valueColor: const AlwaysStoppedAnimation<Color>(
                                  Color(0xffED5C2F),
                                ),
                              )),
                        ),
                        // 中心文字
                        Obx(() => Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  '还可以吃',
                                  style: TextStyle(
                                    fontSize: 10.sp,
                                    color: Colors.white,
                                  ),
                                ),
                                Text(
                                  controller.state.remainingCalories
                                      .toStringAsFixed(0),
                                  style: TextStyle(
                                    fontSize: 18.sp,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white,
                                  ),
                                ),
                                Text(
                                  '/${controller.state.dailyCaloriesTarget.toStringAsFixed(0)}千卡',
                                  style: TextStyle(
                                    fontSize: 8.sp,
                                    color: Colors.grey[400],
                                  ),
                                ),
                              ],
                            )),
                      ],
                    ),
                  ),
                ),

                // 右侧：营养素进度条
                Expanded(
                  flex: 3,
                  child: Column(
                    children: [
                      Obx(() => _buildNutrientProgressBar(
                            icon: Assets.status.carb.image(),
                            label: '碳水化合物',
                            current: controller.state.totalCarbohydrate.value,
                            target: controller.state.dailyCarbTarget,
                            unit: 'g',
                          )),
                      SizedBox(height: 8.h),
                      Obx(() => _buildNutrientProgressBar(
                            icon: Assets.status.protein.image(),
                            label: '蛋白质',
                            current: controller.state.totalProtein.value,
                            target: controller.state.dailyProteinTarget,
                            unit: 'g',
                          )),
                      SizedBox(height: 8.h),
                      Obx(() => _buildNutrientProgressBar(
                            icon: Assets.status.lipid.image(),
                            label: '脂肪',
                            current: controller.state.totalFat.value,
                            target: controller.state.dailyFatTarget,
                            unit: 'g',
                          )),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 16.h),

            // 餐食列表
            _buildFoodRecordList(),
          ],
        ),
      ),
    );
  }

  /// 构建情绪管理模块
  Widget _buildMoodManagementModule(BuildContext context) {
    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 情绪管理标题
          Row(
            children: [
              Assets.status.emotion.image(
                width: 20.w,
                height: 20.w,
              ),
              SizedBox(width: 8.w),
              Text(
                '情绪管理',
                style: TextStyle(
                  fontSize: 17.sp,
                  color: ThemeManager.to.secondaryTextColor,
                ),
              ),
            ],
          ),
          SizedBox(height: 13.5.h),
          Container(
            width: double.infinity,
            height: 1.0,
            color: const Color(0xFF353235),
          ),
          SizedBox(height: 18.5.h),
          // 心情分段条
          _buildMoodSegmentBar(context),
          // 未记录时提示/已选择后的确认卡片/记录后结果卡片
          Obx(() {
            if (hasMoodRecorded.value) {
              return _buildMoodResultCard();
            }
            if (selectedMoodIndex.value >= 0) {
              return _buildMoodConfirmationCard();
            }
            return _buildMoodHint();
          }),
        ],
      ),
    );
  }

  /// 构建心情分段滑块（5 段，可拖拽，松手吸附到最近分段）
  Widget _buildMoodSegmentBar(BuildContext context) {
    final List<Color> segmentColors = [
      const Color(0xFF3662FF), // 非常不愉快 - 蓝紫
      const Color(0xFF2FA7A0), // 不愉快 - 青色
      const Color(0xFF3AB37A), // 无悲无喜 - 绿
      const Color(0xFFCC8E3A), // 愉快 - 橙
      const Color(0xFFB0466B), // 非常愉快 - 品红
    ];

    return Obx(() => Container(
          height: 40.h,
          alignment: Alignment.center,
          child: Stack(
            clipBehavior: Clip.none, // 允许子元素溢出显示
            alignment: Alignment.center,
            children: [
              // 分段背景条
              Row(
                children: List.generate(5, (i) {
                  final bool isActive = selectedMoodIndex.value == i;
                  return Expanded(
                    child: Container(
                      height: 6.h,
                      margin: EdgeInsets.symmetric(horizontal: 3.w),
                      decoration: BoxDecoration(
                        color:
                            segmentColors[i].withOpacity(isActive ? 0.9 : 0.35),
                        borderRadius: BorderRadius.circular(99.r),
                        border: isActive
                            ? Border.all(color: Colors.white, width: 1)
                            : null,
                      ),
                    ),
                  );
                }),
              ),

              // 覆盖透明轨道的 Slider，负责拖动手势
              Positioned.fill(
                top: -6.h,
                bottom: -6.h,
                child: SliderTheme(
                  data: SliderTheme.of(context).copyWith(
                    trackHeight: 19.h,
                    activeTrackColor: Colors.transparent,
                    inactiveTrackColor: Colors.transparent,
                    overlayShape:
                        const RoundSliderOverlayShape(overlayRadius: 0),
                    thumbShape: RoundSliderThumbShape(
                      enabledThumbRadius: 0.1, // 设置为极小，让滑块不可见
                      elevation: 0,
                    ),
                    thumbColor: Colors.transparent,
                  ),
                  child: Slider(
                    value: controller.state.moodValue.value,
                    min: 0.0,
                    max: 1.0,
                    onChanged: (v) {
                      // 检查是否可以记录新情绪（1小时冷却）
                      if (!controller.state.canRecordMood()) {
                        return; // 冷却中，不允许拖动
                      }
                      controller.state.moodValue.value = v;
                    },
                    onChangeEnd: (v) {
                      // 检查是否可以记录新情绪（1小时冷却）
                      if (!controller.state.canRecordMood()) {
                        final remainingMinutes = controller.state.getRemainingCooldownMinutes();
                        Toast.show('每小时只能记录一次情绪，请${remainingMinutes}分钟后再试');
                        return;
                      }
                      
                      // 吸附到最近分段中心：0.1/0.3/0.5/0.7/0.9
                      final double scaled = v * 5.0 - 0.5; // 映射到中心索引
                      final int idx = scaled.round().clamp(0, 4);
                      selectedMoodIndex.value = idx;
                      _updateMoodStateByIndex(idx);
                      final double snapped = (idx + 0.5) / 5.0;
                      controller.state.moodValue.value = snapped;
                    },
                  ),
                ),
              ),

              // 自定义图片滑块
              Positioned(
                left: _getThumbPosition(context),
                child: Assets.status.slider.image(),
              ),
            ],
          ),
        ));
  }

  // 计算滑块位置
  double _getThumbPosition(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final padding = 16.w * 2; // 左右padding
    const thumbWidth = 16.0; // 滑块图片宽度
    final availableWidth = screenWidth - padding - thumbWidth; // 减去滑块宽度
    return controller.state.moodValue.value * availableWidth;
  }

  /// 根据分段索引更新情绪状态
  void _updateMoodStateByIndex(int index) {
    String moodText;
    Color moodColor;
    switch (index) {
      case 0:
        moodText = '非常不愉快';
        moodColor = const Color(0xFF3662FF);
        break;
      case 1:
        moodText = '有点不愉快';
        moodColor = const Color(0xFF2FA7A0);
        break;
      case 2:
        moodText = '无悲无喜';
        moodColor = const Color(0xFF3AB37A);
        break;
      case 3:
        moodText = '有点愉快';
        moodColor = const Color(0xFFCC8E3A);
        break;
      default:
        moodText = '非常愉快';
        moodColor = const Color(0xFFB0466B);
        break;
    }
    controller.state.currentMoodText.value = moodText;
    controller.state.currentMoodColor.value = moodColor;
  }

  /// 根据情绪文本获取对应的图片资源路径（用于记录到控制器）
  String _getMoodIdentifier(String moodText) {
    switch (moodText) {
      case '非常不愉快':
        return 'assets/images/status/very_unhappy.png';
      case '有点不愉快':
        return 'assets/images/status/little_unhappy.png';
      case '无悲无喜':
        return 'assets/images/status/none_feeling.png';
      case '有点愉快':
        return 'assets/images/status/little_happy.png';
      case '非常愉快':
        return 'assets/images/status/very_happy.png';
      default:
        return 'assets/images/status/none_feeling.png';
    }
  }

  /// 构建情绪状态确认卡片
  Widget _buildMoodConfirmationCard() {
    return Obx(() => Container(
          decoration: BoxDecoration(
            color: const Color(0xFF353235),
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Row(
            children: [
              // 情绪图标
              Container(
                  width: 67.w,
                  height: 67.w,
                  decoration: BoxDecoration(
                    color: controller.state.currentMoodColor.value
                        .withOpacity(0.15),
                    borderRadius: BorderRadius.circular(25.r),
                  ),
                  child: Center(child: _buildMoodImageByIndex())),
              SizedBox(width: 12.w),

              // 情绪信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      controller.state.currentMoodText.value,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      '是否确认记录此状态',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                  ],
                ),
              ),

              // 确认和取消按钮
              Row(
                children: [
                  TextButton(
                    onPressed: () async {
                      // 检查是否可以记录新情绪（1小时冷却）
                      if (!controller.state.canRecordMood()) {
                        final remainingMinutes = controller.state.getRemainingCooldownMinutes();
                        Toast.show('每小时只能记录一次情绪，请${remainingMinutes}分钟后再试');
                        selectedMoodIndex.value = -1; // 取消选择
                        return;
                      }
                      
                      print('😊 确认按钮: 开始记录情绪，索引: ${selectedMoodIndex.value}');
                      
                      // 记录情绪标识符到控制器
                      final String moodIdentifier = _getMoodIdentifier(
                          controller.state.currentMoodText.value);
                      Get.find<MoodEmojiController>()
                          .recordMoodEmoji(moodIdentifier);

                      // 更新最后记录时间（立即更新，用于冷却检查）
                      final now = DateTime.now();
                      controller.state.lastEmotionalRecordTime.value = now;
                      print('😊 确认按钮: 更新最后记录时间: ${controller.state.lastEmotionalRecordTime.value}');
                      
                      // 立即设置为已记录状态（在提交之前）
                      hasMoodRecorded.value = true;
                      print('😊 确认按钮: 设置 hasMoodRecorded = true');

                      // 立即添加本地情绪记录（用于显示emoji），避免等待API返回
                      final localRecord = EmotionalStateRecord(
                        emotionalState: '${selectedMoodIndex.value + 1}', // 0-4 -> 1-5
                        recordTime: '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}',
                      );
                      
                      // 将本地记录添加到列表开头
                      final currentList = List<EmotionalStateRecord>.from(controller.state.emotionalStateList);
                      currentList.insert(0, localRecord);
                      controller.state.emotionalStateList.value = currentList;
                      print('😊 确认按钮: 添加本地情绪记录 - 状态: ${localRecord.emotionalState}, 时间: ${localRecord.recordTime}');

                      // 调用 logic 层提交情绪状态
                      await controller.submitEmotionalState(selectedMoodIndex.value);
                      print('😊 确认按钮: 提交情绪状态完成');
                      
                      // 刷新压力情绪数据，让emoji显示在图表上（会从API获取最新数据）
                      await controller.refreshEmotionalData();
                      print('😊 确认按钮: 刷新情绪数据完成');
                    },
                    child: Text(
                      '确认',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Container(
                    width: 1.w,
                    height: 20.h,
                    color: Colors.grey[600],
                  ),
                  TextButton(
                    onPressed: () {
                      // 取消选择
                      selectedMoodIndex.value = -1;
                    },
                    child: Text(
                      '取消',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ));
  }

  /// 未选择时的提示
  Widget _buildMoodHint() {
    return Obx(() {
      final canRecord = controller.state.canRecordMood();
      final remainingMinutes = controller.state.getRemainingCooldownMinutes();
      
      // 如果冷却时间已过，且之前有记录过情绪，自动重置为未记录状态
      if (canRecord && hasMoodRecorded.value) {
        // 延迟执行，避免在build过程中修改状态
        Future.microtask(() {
          hasMoodRecorded.value = false;
          // 保持之前选择的情绪索引，这样会显示确认卡片
        });
      }
      
      return Container(
        margin: EdgeInsets.only(top: 12.h),
        width: double.infinity,
        height: 51.h,
        decoration: BoxDecoration(
          color: const Color(0xFF353235),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Center(
          child: Text(
            canRecord 
                ? '点击标签条，记录你当下的心情'
                : '每小时只能记录一次情绪，请${remainingMinutes}分钟后再试',
            style: TextStyle(
              fontSize: 14.sp, 
              color: canRecord ? Colors.grey[400] : Colors.orange[300],
            ),
          ),
        ),
      );
    });
  }

  /// 记录完成后的结果卡片（当“非常不愉快”时展示跳转文案）
  Widget _buildMoodResultCard() {
    return Obx(() {
      // 检查冷却时间，如果已过期则自动重置为未记录状态
      final canRecord = controller.state.canRecordMood();
      final lastTime = controller.state.lastEmotionalRecordTime.value;
      print('😊 结果卡片: canRecord=$canRecord, hasMoodRecorded=${hasMoodRecorded.value}, lastTime=$lastTime');
      
      if (canRecord && hasMoodRecorded.value) {
        print('😊 结果卡片: 冷却时间已过，重置为未记录状态');
        // 延迟执行，避免在build过程中修改状态
        Future.microtask(() {
          hasMoodRecorded.value = false;
          // 保持之前选择的情绪索引，这样会显示确认卡片
        });
      }
      
      final bool isVeryUnhappy =
          controller.state.currentMoodText.value == '非常不愉快';
      return Container(
        padding: EdgeInsets.all(5.w),
        margin: EdgeInsets.only(top: 12.h),
        decoration: BoxDecoration(
          color: const Color(0xFF353235),
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Row(
          children: [
            // 左侧表情图片发光效果
            Container(
              width: 54.w,
              height: 54.w,
              decoration: BoxDecoration(
                color: controller.state.currentMoodColor.value.withOpacity(0.2),
                borderRadius: BorderRadius.circular(27.r),
              ),
              child: Center(child: _buildMoodImageByIndex(size: 28.w)),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    controller.state.currentMoodText.value,
                    style: TextStyle(
                      fontSize: 15.sp,
                      color: Colors.white,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    isVeryUnhappy ? '状态不好尝试调节一下，跳转至减压 >' : '已记录当前心情，祝你有个好状态',
                    style: TextStyle(fontSize: 12.sp, color: Colors.grey[400]),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 根据当前索引构建图片资源
  Widget _buildMoodImageByIndex({double? size}) {
    final int idx = selectedMoodIndex.value.clamp(0, 4);
    switch (idx) {
      case 0:
        return Assets.status.veryUnhappy.image(width: 67.w, height: 67.h);
      case 1:
        return Assets.status.littleUnhappy.image(width: 67.w, height: 67.h);
      case 2:
        return Assets.status.noneFeeling.image(width: 67.w, height: 67.h);
      case 3:
        return Assets.status.littleHappy.image(width: 67.w, height: 67.h);
      default:
        return Assets.status.veryHappy.image(width: 67.w, height: 67.h);
    }
  }

  /// 构建饮食记录列表
  Widget _buildFoodRecordList() {
    return Obx(() {
      final foodList = controller.state.foodRecordList;
      final isExpanded = controller.state.isExpanded.value;

      if (foodList.isEmpty) {
        return _buildEmptyFoodCard();
      }

      // 决定显示多少条记录
      final displayList = foodList.length <= 3
          ? foodList
          : (isExpanded ? foodList : foodList.take(3).toList());

      return Column(
        children: [
          // 显示食物记录
          ...displayList
              .map((record) => Padding(
                    padding: EdgeInsets.only(bottom: 8.h),
                    child: _buildMealCard(record),
                  ))
              .toList(),

          // 展开/收起按钮（超过3条时显示）
          if (foodList.length > 3) ...[
            SizedBox(height: 8.h),
            GestureDetector(
              onTap: () {
                controller.state.isExpanded.value = !isExpanded;
              },
              child: Container(
                width: double.infinity,
                height: 32.h,
                decoration: BoxDecoration(
                  color: const Color(0xFF353235),
                  borderRadius: BorderRadius.circular(8.r),
                  border: Border.all(
                    color: const Color(0xFF343231),
                    width: 1.0,
                  ),
                ),
                child: Center(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        isExpanded ? '收起' : '展开更多 (${foodList.length - 3})',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[400],
                        ),
                      ),
                      SizedBox(width: 4.w),
                      Icon(
                        isExpanded
                            ? Icons.keyboard_arrow_up
                            : Icons.keyboard_arrow_down,
                        color: Colors.grey[400],
                        size: 16.sp,
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ],
      );
    });
  }

  /// 构建空的饮食卡片
  Widget _buildEmptyFoodCard() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color(0xFF353235),
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Center(
        child: Column(
          children: [
            Icon(
              Icons.restaurant,
              color: Colors.grey[400],
              size: 32.sp,
            ),
            SizedBox(height: 8.h),
            Text(
              '暂无饮食记录',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[400],
              ),
            ),
            SizedBox(height: 4.h),
            Text(
              '点击上方"添加"按钮记录您的饮食',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[500],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建单个餐食卡片
  Widget _buildMealCard(FoodRecord record) {
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: const Color(0xFF353235),
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Row(
        children: [
          // 餐食图片
          Container(
            width: 60.w,
            height: 60.w,
            decoration: BoxDecoration(
              color: Colors.grey[700],
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: record.imageUrl == null
                ? Center(
                    child: Icon(
                      Icons.restaurant,
                      color: Colors.grey[400],
                      size: 24.sp,
                    ),
                  )
                : ClipRRect(
                    borderRadius: BorderRadius.circular(8.r),
                    child: Image.network(
                      _buildImageUrl(record.imageUrl!),
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Center(
                          child: Icon(
                            Icons.restaurant,
                            color: Colors.grey[400],
                            size: 24.sp,
                          ),
                        );
                      },
                    ),
                  ),
          ),
          SizedBox(width: 12.w),

          // 餐食信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Row(
                        children: [
                          Flexible(
                            child: Text(
                              record.foodName ?? '未知食物',
                              style: TextStyle(
                                fontSize: 14.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          SizedBox(width: 6.w),
                          Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 6.w,
                              vertical: 2.h,
                            ),
                            decoration: BoxDecoration(
                              color: const Color(0xff3B393B),
                              borderRadius: BorderRadius.circular(4.r),
                            ),
                            child: Text(
                              record.getMealTypeText(),
                              style: TextStyle(
                                fontSize: 11.sp,
                                color: const Color(0xff908E8D),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Text(
                      record.calories != null
                          ? '${record.calories!.toStringAsFixed(0)} kcal'
                          : '-- kcal',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: const Color(0xffED5C2F),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 4.h),
                Text(
                  record.recordDate ?? '--',
                  style: TextStyle(
                    fontSize: 10.sp,
                    color: Colors.grey[400],
                  ),
                ),
                SizedBox(height: 8.h),
                Row(
                  children: [
                    Text(
                      '碳水: ${record.carbohydrate?.toStringAsFixed(0) ?? '--'}g',
                      style: TextStyle(
                        fontSize: 10.sp,
                        color: Colors.white,
                      ),
                    ),
                    SizedBox(width: 12.w),
                    Text(
                      '蛋白质: ${record.protein?.toStringAsFixed(0) ?? '--'}g',
                      style: TextStyle(
                        fontSize: 10.sp,
                        color: Colors.white,
                      ),
                    ),
                    SizedBox(width: 12.w),
                    Text(
                      '脂肪: ${record.fat?.toStringAsFixed(0) ?? '--'}g',
                      style: TextStyle(
                        fontSize: 10.sp,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String _buildImageUrl(String relative) {
    const String base = 'https://api.azlg.com/prod-api';
    if (relative.startsWith('http')) return relative;
    if (relative.startsWith('/')) return '$base$relative';
    return '$base/$relative';
  }

  /// 构建压力模块
  Widget _buildPressureModule() {
    return GestureDetector(
        onTap: () {
          Get.toNamed(PressureRoutes.pressure);
        },
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: const Color(0xFF353235),
            borderRadius: BorderRadius.circular(8.r),
          ),
          padding: EdgeInsets.all(12.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 压力标题和时间
              Row(
                children: [
                  Text(
                    '压力',
                    style: TextStyle(
                      fontSize: 15.sp,
                      color: ThemeManager.to.secondaryTextColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const Spacer(),
                  Obx(() => Text(
                        '${controller.state.currentStress.value} ${controller.state.stressStatus}',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: controller.state.stressColor,
                        ),
                      )),
                ],
              ),
              SizedBox(height: 4.h),
              Obx(() {
                // 使用API返回的时间数据
                final recordDate = controller.state.emotionalRecordDate.value;
                final weekName = controller.state.emotionalWeekName.value;
                final recordTime = controller.state.emotionalRecordTime.value;

                // 如果有API数据，使用API数据；否则使用当前时间
                final timeStr = recordDate.isNotEmpty &&
                        weekName.isNotEmpty &&
                        recordTime.isNotEmpty
                    ? '$recordDate,$weekName,$recordTime'
                    : _buildCurrentTimeString();

                return Text(
                  timeStr,
                  style: TextStyle(
                    fontSize: 10.sp,
                    color: Colors.grey[400],
                  ),
                );
              }),
              SizedBox(height: 13.h),
              Container(
                width: double.infinity,
                height: 1.0,
                color: const Color(0xFF212121),
              ),
              SizedBox(height: 12.h),

              // 压力图表
              const PressureChart(),
            ],
          ),
        ));
  }

  /// 构建当前时间字符串（作为后备方案）
  String _buildCurrentTimeString() {
    final now = DateTime.now();
    final weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    final weekday = weekdays[now.weekday - 1];
    return '${now.year}/${now.month}/${now.day},$weekday,${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
  }

  /// 构建营养素进度条
  Widget _buildNutrientProgressBar({
    required Image icon,
    required String label,
    required double current,
    required double target,
    required String unit,
  }) {
    final progress = current / target;

    return Row(
      children: [
        icon,
        SizedBox(width: 6.w),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    label,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.white,
                    ),
                  ),
                  Text(
                    '${current.toStringAsFixed(1)}/${target.toStringAsFixed(0)}$unit',
                    style: TextStyle(
                      fontSize: 10.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 4.h),
              LinearProgressIndicator(
                value: progress,
                backgroundColor: Colors.grey[800],
                valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
                minHeight: 4.h,
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建今日事件小计模块
  Widget _buildTodayEventsSummary() {
    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题和添加按钮
          Row(
            children: [
              GestureDetector(
                onTap: () {
                  // 跳转到事件小计页面
                  Get.toNamed(EventSummaryRoutes.eventSummary);
                },
                child: Row(
                  children: [
                    Assets.status.event.image(width: 17.w, height: 17.h),
                    SizedBox(width: 12.w),
                    Text(
                      '今日事件小计',
                      style: TextStyle(
                        fontSize: 17.sp,
                        color: ThemeManager.to.secondaryTextColor,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              ),
              Spacer(),
              GestureDetector(
                onTap: () => Get.toNamed(DailyEventsRoutes.dailyEvents),
                child: Container(
                  width: 63.w,
                  height: 27.h,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: const Color(0xFF343231),
                      width: 1.0,
                    ),
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Assets.status.add.image(
                        width: 8.w,
                        height: 8.w,
                        color: ThemeManager.to.buttonTextColor,
                      ),
                      SizedBox(width: 4.w),
                      Text(
                        '添加',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: ThemeManager.to.buttonTextColor,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 13.5.h),
          Container(
            width: double.infinity,
            height: 1.0,
            color: const Color(0xFF353235),
          ),
          SizedBox(height: 13.5.h),
          // 介绍文字 - 始终显示
          Align(
            alignment: Alignment.center,
            child: Text(
              '你今天做了那些事情,是否会影响身体评分,',
              style: TextStyle(
                fontSize: 12.sp,
                color: ThemeManager.to.buttonTextColor,
              ),
            ),
          ),
          Align(
            alignment: Alignment.center,
            child: Text(
              '写下来让小A管家检测打分吧!',
              style: TextStyle(
                fontSize: 12.sp,
                color: ThemeManager.to.buttonTextColor,
              ),
            ),
          ),
          SizedBox(height: 16.h),

          // 根据数据情况显示内容
          Obx(() {
            if (controller.state.isLoadingDailyEvents.value) {
              return Container(
                padding: EdgeInsets.all(20.w),
                child: const Center(
                  child: CircularProgressIndicator(
                    color: Colors.orange,
                  ),
                ),
              );
            }

            final events = controller.state.dailyEventsList;

            if (events.isEmpty) {
              return const SizedBox.shrink();
            } else {
              // 有数据时显示事件列表
              return _buildEventsList();
            }
          }),
        ],
      ),
    );
  }

  /// 处理卡片点击事件（跳转到详情页面）
  void _handleCardTap(String title) {
    switch (title) {
      case '心率':
        // 跳转到心率详情页面
        Get.toNamed(HeartRateRoutes.heartRate);
        break;
      case '心率变异性':
        // 跳转到心率变异性详情页面
        Get.toNamed(HeartRateRoutes.heartRateVariability);
        break;
      case '睡眠':
        // 跳转到睡眠详情页面
        Get.toNamed(AppRoutes.sleep);
        break;
      case '血氧饱和度':
        // 跳转到血氧详情页面
        Get.toNamed(BloodOxygenRoutes.bloodOxygen);
        break;
      case '活动':
        // 跳转到活动详情页面
        Get.toNamed(AppRoutes.activity);
        break;
      case '锻炼记录':
        // 跳转到锻炼记录页面
        Get.toNamed(ExerciseRoutes.exerciseRecord);
        break;
      case '生理周期':
        // 跳转到生理周期页面
        Get.toNamed(MenstrualCycleRoutes.calendar);
        break;
      case '压力':
        // 跳转到压力详情页面
        Get.toNamed(PressureRoutes.pressure);
        break;
      default:
        print('点击了卡片: $title');
        break;
    }
  }

  /// 处理卡片按钮点击事件（触发测量或操作）
  void _handleCardButtonTap(String title) {
    switch (title) {
      case '心率':
        // 检查是否正在测量
        if (ringLogic.isHeartRateMeasuring) {
          controller.stopHeartRateMeasurement();
        } else {
          controller.startHeartRateMeasurement();
        }
        break;
      case '心率变异性':
        // 检查是否正在测量
        if (ringLogic.isHrvMeasuring) {
          controller.stopHrvMeasurement();
        } else {
          controller.startHrvMeasurement();
        }
        break;
      case '睡眠':
        // 睡眠数据查询
        // controller.querySleepData();
        break;
      case '血氧饱和度':
        // 检查是否正在测量
        if (ringLogic.isBloodOxygenMeasuring) {
          controller.stopBloodOxygenMeasurement();
        } else {
          controller.startBloodOxygenMeasurement();
        }
        break;
      case '活动':
        // 获取活动数据
        Get.toNamed(ActivityRoutes.activity);
        break;
      case '锻炼记录':
        // 跳转到锻炼选择页面（开始锻炼）
        Get.toNamed(ExerciseRoutes.exercise);
        break;
      case '压力':
        // 检查是否正在测量
        if (ringLogic.isStressMeasuring) {
          controller.stopStressMeasurement();
        } else {
          controller.startStressMeasurement();
        }
        break;
      default:
        print('点击了按钮: $title');
        break;
    }
  }

  /// 构建事件列表（仅在有数据时调用）
  Widget _buildEventsList() {
    final events = controller.state.dailyEventsList;

    return Column(
      children: events.map((event) {
        final isLast = events.indexOf(event) == events.length - 1;
        return Column(
          children: [
            _buildEventCard(
              eventText: event.eventText,
              score: event.score,
              scoreColor: event.isPositive
                  ? const Color(0xff3CE89B) // 绿色为正分
                  : const Color(0xffED5C2F), // 橙色为负分
              aiComment: event.aiComment,
            ),
            if (!isLast) SizedBox(height: 12.h),
          ],
        );
      }).toList(),
    );
  }

  /// 构建事件卡片
  Widget _buildEventCard({
    required String eventText,
    required String score,
    required Color scoreColor,
    required String aiComment,
  }) {
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        image: DecorationImage(
          image: AssetImage(Assets.status.eventBg.path),
          fit: BoxFit.cover,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 事件和分数
          Row(
            children: [
              Expanded(
                child: Text(
                  eventText,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              Text(
                score,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: scoreColor,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          SizedBox(height: 8.h),

          // AI助手评论
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 12.w,
                      vertical: 8.h,
                    ),
                    decoration: BoxDecoration(
                      // color: Colors.black.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Assets.status.ai.image(width: 20.w, height: 20.h),
                        SizedBox(width: 5.w),
                        Expanded(
                          child: Text(
                            aiComment,
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.white,
                            ),
                            softWrap: true,
                            overflow: TextOverflow.visible,
                          ),
                        ),
                      ],
                    )),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建生理周期图表（带图例）
  Widget _buildMenstrualCycleChartWithLegend() {
    return Obx(() {
      final cycleData = controller.state.menstrualCycleData.value;
      final bool hasData = cycleData != null && cycleData.days.isNotEmpty;

      return Column(
        children: [
          // 柱状图
          Expanded(
            child: _buildMenstrualCycleChart(hasData, cycleData),
          ),
          SizedBox(height: 3.h),
          // 图例
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 6.w,
                height: 6.w,
                decoration: const BoxDecoration(
                  color: Color(0xFFFF931F),
                  shape: BoxShape.circle,
                ),
              ),
              SizedBox(width: 3.w),
              Text(
                '排卵期',
                style: TextStyle(
                  fontSize: 10.sp,
                  color: const Color(0xff908E8D),
                ),
              ),
              SizedBox(width: 6.w),
              Container(
                width: 6.w,
                height: 6.w,
                decoration: const BoxDecoration(
                  color: Color(0xFFFF5070),
                  shape: BoxShape.circle,
                ),
              ),
              SizedBox(width: 3.w),
              Text(
                '生理期',
                style: TextStyle(
                  fontSize: 10.sp,
                  color: const Color(0xff908E8D),
                ),
              ),
            ],
          ),
        ],
      );
    });
  }

  /// 构建生理周期图表
  Widget _buildMenstrualCycleChart(
      bool hasData, MenstrualCycleData? cycleData) {
    // 无数据时的灰色柱状图
    const Color emptyColor = Color(0xFF565656);

    // 获取月份（优先使用数据中的月份）
    final currentMonth = cycleData?.month ?? '${DateTime.now().month}月';

    // 构建柱状图数据
    List<BarChartGroupData> barGroups = [];

    if (hasData && cycleData != null && cycleData.days.isNotEmpty) {
      for (int i = 0; i < cycleData.days.length && i < 7; i++) {
        final dayData = cycleData.days[i];
        barGroups.add(_buildBarGroup(i, 68, dayData.getColor()));
      }
    } else {
      for (int i = 0; i < 7; i++) {
        barGroups.add(_buildBarGroup(i, 68, emptyColor));
      }
    }

    List<String> weekLabels = [];
    List<String> dateLabels = [];

    if (hasData && cycleData != null && cycleData.days.isNotEmpty) {
      for (int i = 0; i < cycleData.days.length && i < 7; i++) {
        weekLabels.add(cycleData.days[i].weekName);
        dateLabels.add(cycleData.days[i].value);
      }
      final defaultWeeks = ['一', '二', '三', '四', '五', '六', '日'];
      for (int i = cycleData.days.length; i < 7; i++) {
        weekLabels.add(defaultWeeks[i]);
        dateLabels.add('--');
      }
    } else {
      weekLabels = ['一', '二', '三', '四', '五', '六', '日'];
      dateLabels = ['--', '--', '--', '--', '--', '--', '--'];
    }

    return Column(
      children: [
        // 顶部星期标签
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 0.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children:
                weekLabels.map((label) => _buildWeekLabel(label)).toList(),
          ),
        ),
        // 柱状图和日期标签叠加
        Expanded(
          child: Stack(
            children: [
              // 柱状图
              BarChart(
                BarChartData(
                  barTouchData: BarTouchData(enabled: false),
                  titlesData: const FlTitlesData(
                    show: false,
                    leftTitles:
                        AxisTitles(sideTitles: SideTitles(showTitles: false)),
                    rightTitles:
                        AxisTitles(sideTitles: SideTitles(showTitles: false)),
                    topTitles:
                        AxisTitles(sideTitles: SideTitles(showTitles: false)),
                    bottomTitles:
                        AxisTitles(sideTitles: SideTitles(showTitles: false)),
                  ),
                  borderData: FlBorderData(show: false),
                  barGroups: barGroups,
                  gridData: const FlGridData(show: false),
                  alignment: BarChartAlignment.spaceAround,
                  maxY: 100,
                ),
              ),
              // 日期标签叠加在柱子底部
              Positioned(
                bottom: 4.h,
                left: 0,
                right: 0,
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 0.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: dateLabels
                        .map((label) => _buildDateLabel(label))
                        .toList(),
                  ),
                ),
              ),
            ],
          ),
        ),

        SizedBox(height: 4.h),

        // 底部月份标签
        Text(
          currentMonth,
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  /// 构建星期标签
  Widget _buildWeekLabel(String text) {
    return Text(
      text,
      style: TextStyle(
        fontSize: 10.sp,
        color: const Color(0xff5a5a5a),
        fontWeight: FontWeight.w500,
      ),
    );
  }

  /// 构建日期标签
  Widget _buildDateLabel(String text) {
    return Text(
      text,
      style: TextStyle(
        fontSize: 10.sp,
        color: Colors.white, // 白色400透明度
        fontWeight: FontWeight.w400,
      ),
    );
  }

  /// 构建柱状图组
  BarChartGroupData _buildBarGroup(int x, double height, Color color) {
    return BarChartGroupData(
      x: x,
      barRods: [
        BarChartRodData(
          toY: height,
          color: color,
          width: 16.w, // 宽度16px
          borderRadius: BorderRadius.circular(5.7.r), // 圆角5.7px
        )
      ],
    );
  }

  /// 构建活动卡片
  Widget _buildActivityCard() {
    return Obx(() {
      // 从API获取活动数据
      final activityData = controller.state.activityData.value;
      final hasData = activityData != null;

      return Column(
        children: [
          // 多环进度图
          Expanded(
            flex: 3,
            child: Center(
              child: Stack(
                alignment: Alignment.center,
                children: [
                  // 最外层环 - 活动时间（绿色或灰色）
                  SizedBox(
                    width: 80.w,
                    height: 80.w,
                    child: CircularProgressIndicator(
                      value: hasData ? controller.state.sportTimeProgress : 0.0,
                      strokeWidth: 6.w,
                      backgroundColor: const Color(0xFF2A2A2A),
                      valueColor: AlwaysStoppedAnimation<Color>(hasData
                          ? const Color(0xFFc89d06)
                          : const Color(0xFF2A2A2A)),
                    ),
                  ),
                  // 中间层环 - 卡路里（橙色或灰色）
                  SizedBox(
                    width: 65.w,
                    height: 65.w,
                    child: CircularProgressIndicator(
                      value: hasData
                          ? controller.state.caloriesProgressForActivity
                          : 0.0,
                      strokeWidth: 6.w,
                      backgroundColor: const Color(0xFF2A2A2A),
                      valueColor: AlwaysStoppedAnimation<Color>(hasData
                          ? const Color(0xFFe86429)
                          : const Color(0xFF2A2A2A)),
                    ),
                  ),
                  // 最内层环 - 步数（蓝色或灰色）
                  SizedBox(
                    width: 50.w,
                    height: 50.w,
                    child: CircularProgressIndicator(
                      value: hasData ? controller.state.stepsProgress : 0.0,
                      strokeWidth: 6.w,
                      backgroundColor: const Color(0xFF2A2A2A),
                      valueColor: AlwaysStoppedAnimation<Color>(hasData
                          ? const Color(0xFF4A90E2)
                          : const Color(0xFF0d948e)),
                    ),
                  ),
                ],
              ),
            ),
          ),

          // 底部数据显示
          Expanded(
            flex: 2,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                // 步数
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      hasData ? '${activityData.steps.toInt()}' : '--',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      hasData ? '/${activityData.goalsSteps.toInt()}步' : '--',
                      style: TextStyle(
                        fontSize: 8.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                    SizedBox(height: 2.h),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          width: 6.w,
                          height: 6.w,
                          decoration: BoxDecoration(
                            color: hasData
                                ? const Color(0xFF4A90E2)
                                : const Color(0xFF2A2A2A),
                            shape: BoxShape.circle,
                          ),
                        ),
                        SizedBox(width: 2.w),
                        Text(
                          '步数',
                          style: TextStyle(
                            fontSize: 8.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),

                // 卡路里
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      hasData ? '${activityData.calories.toInt()}' : '--',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      hasData
                          ? '/${activityData.goalsCalories.toInt()}卡'
                          : '--',
                      style: TextStyle(
                        fontSize: 8.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                    SizedBox(height: 2.h),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          width: 6.w,
                          height: 6.w,
                          decoration: BoxDecoration(
                            color: hasData
                                ? const Color(0xFFFF6B35)
                                : const Color(0xFF2A2A2A),
                            shape: BoxShape.circle,
                          ),
                        ),
                        SizedBox(width: 2.w),
                        Text(
                          '卡路里',
                          style: TextStyle(
                            fontSize: 8.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),

                // 活动时间
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      hasData ? '${activityData.sportTime.toInt()}' : '--',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      hasData
                          ? '/${activityData.goalsSportTime.toInt()}分钟'
                          : '--',
                      style: TextStyle(
                        fontSize: 8.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                    SizedBox(height: 2.h),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          width: 6.w,
                          height: 6.w,
                          decoration: BoxDecoration(
                            color: hasData
                                ? const Color(0xFF00D4AA)
                                : const Color(0xFF2A2A2A),
                            shape: BoxShape.circle,
                          ),
                        ),
                        SizedBox(width: 2.w),
                        Text(
                          '活动时间',
                          style: TextStyle(
                            fontSize: 8.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      );
    });
  }

  /// 构建锻炼记录统计卡片
  Widget _buildExerciseStatsCard() {
    return Obx(() {
      final exerciseData = controller.state.exerciseRecordData.value;
      final hasData = exerciseData != null;

      return Column(
        children: [
          // 统计数据列表
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildExerciseStatRow(
                  '运动总次数',
                  hasData && exerciseData.total != null
                      ? '${exerciseData.total}次'
                      : '--',
                ),
                Container(
                  height: 1.h,
                  color: Colors.grey[800],
                ),
                _buildExerciseStatRow(
                  '运动总时长',
                  hasData && exerciseData.exerciseTime != null
                      ? '${exerciseData.exerciseTime}分钟'
                      : '--',
                ),
                Container(
                  height: 1.h,
                  color: Colors.grey[800],
                ),
                _buildExerciseStatRow(
                  '运动总卡路里',
                  hasData && exerciseData.exerciseCalorie != null
                      ? '${exerciseData.exerciseCalorie}千卡'
                      : '--',
                ),
              ],
            ),
          ),
        ],
      );
    });
  }

  /// 构建锻炼统计行
  Widget _buildExerciseStatRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 4.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.grey[400],
            ),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }
}

/// 构建健康图表
Widget _buildHealthChart(
    String chartType, bool isConnected, StatusLogic controller) {
  switch (chartType) {
    case 'heartRate':
      return _buildHeartRateChart(controller);
    case 'hrv':
      return _buildHrvChart(controller);
    case 'sleep':
      return _buildSleepChart(controller);
    case 'bloodOxygen':
      return _buildBloodOxygenChart(controller);
    default:
      return Container();
  }
}

/// 构建心率图表
Widget _buildHeartRateChart(StatusLogic controller) {
  return Obx(() {
    final heartRateData = controller.state.heartRateList;

    if (heartRateData.isEmpty) {
      return Center(
        child: Text(
          '暂无数据',
          style: TextStyle(
            color: Colors.grey[400],
            fontSize: 12.sp,
          ),
        ),
      );
    }

    // 获取睡眠时间段（从API返回的startTime和endTime）
    final startTimeStr = controller.state.heartRateStartTime.value;
    final endTimeStr = controller.state.heartRateEndTime.value;

    // 解析睡眠开始和结束时间为小时数
    double sleepStartHour = 0;
    double sleepEndHour = 8; // 默认值

    if (startTimeStr.isNotEmpty) {
      final startParts = startTimeStr.split(':');
      if (startParts.length == 2) {
        sleepStartHour = (double.tryParse(startParts[0]) ?? 0) +
            (double.tryParse(startParts[1]) ?? 0) / 60;
      }
    }

    if (endTimeStr.isNotEmpty) {
      final endParts = endTimeStr.split(':');
      if (endParts.length == 2) {
        sleepEndHour = (double.tryParse(endParts[0]) ?? 0) +
            (double.tryParse(endParts[1]) ?? 0) / 60;
      }
    }

    // 将时间标签转换为小时数（例如 "01:00" -> 1.0）
    // 只收集有效数据点（value > 0）
    List<FlSpot> allSpots = [];

    for (var point in heartRateData) {
      if (point.value > 0) {
        final timeParts = point.timeLabel.split(':');
        if (timeParts.length == 2) {
          final hour = double.tryParse(timeParts[0]) ?? 0;
          final minute = double.tryParse(timeParts[1]) ?? 0;
          final timeValue = hour + (minute / 60);
          allSpots.add(FlSpot(timeValue, point.value.toDouble()));
        }
      }
    }

    if (allSpots.isEmpty) {
      return Center(
        child: Text(
          '暂无有效数据',
          style: TextStyle(
            color: Colors.grey[400],
            fontSize: 12.sp,
          ),
        ),
      );
    }

    // 按时间排序
    allSpots.sort((a, b) => a.x.compareTo(b.x));

    // 使用线性插值填充数据点，创建连续的线段
    List<FlSpot> interpolatedSpots = [];
    
    for (int i = 0; i < allSpots.length; i++) {
      interpolatedSpots.add(allSpots[i]);
      
      // 如果不是最后一个点，在当前点和下一个点之间插值
      if (i < allSpots.length - 1) {
        final current = allSpots[i];
        final next = allSpots[i + 1];
        final timeDiff = next.x - current.x;
        
        // 如果两点之间的时间间隔大于0.1小时（6分钟），进行插值
        if (timeDiff > 0.1) {
          // 计算需要插入多少个点（每0.1小时一个点）
          final numPoints = (timeDiff / 0.1).floor();
          
          for (int j = 1; j < numPoints; j++) {
            final ratio = j / numPoints;
            final interpolatedX = current.x + timeDiff * ratio;
            final interpolatedY = current.y + (next.y - current.y) * ratio;
            interpolatedSpots.add(FlSpot(interpolatedX, interpolatedY));
          }
        }
      }
    }

    // 按时间重新排序插值后的点
    interpolatedSpots.sort((a, b) => a.x.compareTo(b.x));

    // 将连续的线段分成多个部分，根据是否跨越睡眠时段边界
    List<List<FlSpot>> sleepSegments = [];
    List<List<FlSpot>> daytimeSegments = [];
    
    List<FlSpot> currentSegment = [];
    bool? lastWasSleep;

    for (var spot in interpolatedSpots) {
      // 判断是否在睡眠时间段内
      bool isInSleepPeriod = false;

      if (sleepStartHour < sleepEndHour) {
        // 睡眠时间在同一天内（例如：01:15 - 08:11）
        isInSleepPeriod = spot.x >= sleepStartHour && spot.x <= sleepEndHour;
      } else {
        // 睡眠时间跨越午夜（例如：22:00 - 08:00）
        isInSleepPeriod = spot.x >= sleepStartHour || spot.x <= sleepEndHour;
      }

      // 如果类型改变（从睡眠到白天，或从白天到睡眠）
      if (lastWasSleep != null && lastWasSleep != isInSleepPeriod) {
        // 保存当前线段
        if (currentSegment.isNotEmpty) {
          // 添加当前点到当前线段，使线段连接
          currentSegment.add(spot);
          
          if (lastWasSleep) {
            sleepSegments.add(List.from(currentSegment));
          } else {
            daytimeSegments.add(List.from(currentSegment));
          }
          
          // 开始新线段，从当前点开始
          currentSegment = [spot];
        }
      } else {
        currentSegment.add(spot);
      }

      lastWasSleep = isInSleepPeriod;
    }

    // 添加最后的线段
    if (currentSegment.isNotEmpty) {
      if (lastWasSleep == true) {
        sleepSegments.add(currentSegment);
      } else {
        daytimeSegments.add(currentSegment);
      }
    }

    // 计算Y轴范围
    final allValues = allSpots.map((s) => s.y).toList();
    final minValue = allValues.reduce((a, b) => a < b ? a : b);
    final maxValue = allValues.reduce((a, b) => a > b ? a : b);
    final minY = (minValue - 10).clamp(40, 200).toDouble();
    final maxY = (maxValue + 10).clamp(60, 220).toDouble();

    // 创建线条数据
    List<LineChartBarData> allLines = [];

    // 添加所有睡眠时段线条（蓝色）
    for (var segment in sleepSegments) {
      if (segment.isNotEmpty) {
        allLines.add(
          LineChartBarData(
            spots: segment,
            isCurved: true,
            curveSmoothness: 0.35,
            preventCurveOverShooting: true,
            color: const Color(0xFF4A90E2),
            barWidth: 2.5,
            dotData: const FlDotData(show: false),
            belowBarData: BarAreaData(
              show: true,
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  const Color(0xFF4A90E2).withOpacity(0.3),
                  const Color(0xFF4A90E2).withOpacity(0.0),
                ],
              ),
            ),
          ),
        );
      }
    }

    // 添加所有白天时段线条（红色）
    for (var segment in daytimeSegments) {
      if (segment.isNotEmpty) {
        allLines.add(
          LineChartBarData(
            spots: segment,
            isCurved: true,
            curveSmoothness: 0.35,
            preventCurveOverShooting: true,
            color: const Color(0xFFFF6B6B),
            barWidth: 2.5,
            dotData: const FlDotData(show: false),
            belowBarData: BarAreaData(
              show: true,
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  const Color(0xFFFF6B6B).withOpacity(0.3),
                  const Color(0xFFFF6B6B).withOpacity(0.0),
                ],
              ),
            ),
          ),
        );
      }
    }

    return LineChart(
      LineChartData(
        lineTouchData: const LineTouchData(enabled: false),
        gridData: const FlGridData(show: false),
        titlesData: FlTitlesData(
          show: true,
          leftTitles:
              const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          rightTitles:
              const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          topTitles:
              const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 18,
              interval: 12,
              getTitlesWidget: (value, meta) {
                if (value == 0 || value == 12 || value == 24) {
                  return Padding(
                    padding: EdgeInsets.only(top: 4.h),
                    child: Text(
                      '${value.toInt()}:00',
                      style: TextStyle(
                        color: const Color(0xFF5A5A5A),
                        fontSize: 8.sp,
                      ),
                    ),
                  );
                }
                return const SizedBox.shrink();
              },
            ),
          ),
        ),
        borderData: FlBorderData(show: false),
        lineBarsData: allLines,
        minX: 0,
        maxX: 24,
        minY: minY,
        maxY: maxY,
      ),
    );
  });
}

/// 构建心率变异性图表
Widget _buildHrvChart(StatusLogic controller) {
  return Obx(() {
    final hrvData = controller.state.hrvList;

    // 将时间标签转换为小时数（例如 "01:00" -> 1.0）
    // 只收集有效数据点（value > 0）
    List<FlSpot> spots = [];
    for (var point in hrvData) {
      if (point.value > 0) {
        final timeParts = point.timeLabel.split(':');
        if (timeParts.length == 2) {
          final hour = double.tryParse(timeParts[0]) ?? 0;
          final minute = double.tryParse(timeParts[1]) ?? 0;
          final timeValue = hour + (minute / 60);
          spots.add(FlSpot(timeValue, point.value.toDouble()));
        }
      }
    }

    // 如果没有数据，显示空状态
    if (spots.isEmpty) {
      return Container(
        height: 80.h,
        child: Center(
          child: Text(
            '暂无数据',
            style: TextStyle(
              color: Colors.grey[400],
              fontSize: 12.sp,
            ),
          ),
        ),
      );
    }

    // 按时间排序
    spots.sort((a, b) => a.x.compareTo(b.x));

    // 计算Y轴范围
    final allValues = spots.map((s) => s.y).toList();
    final minValue = allValues.reduce((a, b) => a < b ? a : b);
    final maxValue = allValues.reduce((a, b) => a > b ? a : b);
    final minY = (minValue - 10).clamp(0, 200).toDouble();
    final maxY = (maxValue + 10).clamp(20, 220).toDouble();

    return LineChart(
      LineChartData(
        lineTouchData: const LineTouchData(enabled: false),
        gridData: const FlGridData(show: false),
        titlesData: FlTitlesData(
          show: true,
          leftTitles:
              const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          rightTitles:
              const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          topTitles:
              const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 18,
              interval: 12,
              getTitlesWidget: (value, meta) {
                if (value == 0 || value == 12 || value == 24) {
                  return Padding(
                    padding: EdgeInsets.only(top: 4.h),
                    child: Text(
                      '${value.toInt()}:00',
                      style: TextStyle(
                        color: const Color(0xFF5A5A5A),
                        fontSize: 8.sp,
                      ),
                    ),
                  );
                }
                return const SizedBox.shrink();
              },
            ),
          ),
        ),
        borderData: FlBorderData(show: false),
        lineBarsData: [
          LineChartBarData(
            spots: spots,
            isCurved: true,
            color: const Color(0xFFFF6B35),
            barWidth: 2,
            dotData: const FlDotData(show: false),
            belowBarData: BarAreaData(
              show: true,
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  const Color(0xFFFF6B35).withOpacity(0.3),
                  const Color(0xFFFF6B35).withOpacity(0.0),
                ],
              ),
            ),
          ),
        ],
        minX: 0,
        maxX: 24,
        minY: minY,
        maxY: maxY,
      ),
    );
  });
}

/// 构建睡眠图表
Widget _buildSleepChart(StatusLogic controller) {
  return Obx(() {
    // 从 controller.state 获取睡眠信息数据
    final sleepCardData = controller.state.sleepCardData.value;
    final hasData = sleepCardData != null && sleepCardData.maps != null;

    if (!hasData) {
      return Center(
        child: Text(
          '暂无数据',
          style: TextStyle(
            color: Colors.grey[400],
            fontSize: 12.sp,
          ),
        ),
      );
    }

    // 获取开始和结束时间
    final startTime = sleepCardData.startDate.split(' ').length > 1
        ? sleepCardData.startDate.split(' ')[1].substring(0, 5)
        : '--';
    final endTime = sleepCardData.endDate.split(' ').length > 1
        ? sleepCardData.endDate.split(' ')[1].substring(0, 5)
        : '--';

    return LayoutBuilder(
      builder: (context, constraints) {
        // 计算时间标签的高度（文字高度 + padding）
        final timeLabelHeight = 8.sp * 1.2 + 2.h; // 文字高度 + 上方间距
        // 图表可用高度 = 总高度 - 时间标签高度
        final chartHeight = constraints.maxHeight - timeLabelHeight;
        
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 图表区域 - 使用固定高度
            SizedBox(
              height: chartHeight,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2.h),
                child: CustomPaint(
                  painter: SleepStageTimelinePainter(
                    sleepMaps: sleepCardData.maps!,
                    startDate: sleepCardData.startDate,
                    endDate: sleepCardData.endDate,
                  ),
                  child: Container(),
                ),
              ),
            ),
            SizedBox(height: 2.h),
            // 时间标签
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 8.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    startTime,
                    style: TextStyle(
                      fontSize: 8.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                  Text(
                    endTime,
                    style: TextStyle(
                      fontSize: 8.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  });
}

/// 睡眠阶段时间轴绘制器
class SleepStageTimelinePainter extends CustomPainter {
  final Map<String, dynamic> sleepMaps;
  final String startDate;
  final String endDate;

  SleepStageTimelinePainter({
    required this.sleepMaps,
    required this.startDate,
    required this.endDate,
  });

  @override
  void paint(Canvas canvas, Size size) {
    // 睡眠阶段颜色定义（与睡眠页面一致）
    const Map<String, Color> stageColors = {
      'awake': Color(0xFFE0E0E0), // 清醒 - 浅灰色
      'rem': Color(0xFFFFB366), // 快速眼动 - 浅橙色
      'light': Color(0xFFFF8C42), // 浅睡眠 - 橙色
      'deep': Color(0xFF4B241A), // 深睡眠 - 深棕色
    };

    // 解析开始和结束时间
    final startDateTime = DateTime.parse(startDate);
    final endDateTime = DateTime.parse(endDate);
    final double totalDuration =
        endDateTime.difference(startDateTime).inMinutes.toDouble();

    final double chartHeight = size.height;
    final double chartWidth = size.width;
    final double stageHeight = chartHeight / 4; // 每个睡眠阶段的高度

    // 收集所有睡眠片段
    final List<Map<String, dynamic>> sleepData = [];

    sleepMaps.forEach((key, segments) {
      for (var segment in segments) {
        if (segment is Map<String, dynamic>) {
          final startTime = segment['startTime'] as String;
          final totalTime = segment['totalTime'] as int;
          final sleepType = segment['sleepType'] as int;

          // 解析时间字符串 "HH:mm"
          final startParts = startTime.split(':');
          final startHour = int.parse(startParts[0]);
          final startMinute = int.parse(startParts[1]);

          // 创建片段开始时间
          var segmentStart = DateTime(startDateTime.year, startDateTime.month,
              startDateTime.day, startHour, startMinute);

          // 如果片段时间早于睡眠开始时间，说明跨天了
          if (segmentStart.isBefore(startDateTime)) {
            segmentStart = segmentStart.add(Duration(days: 1));
          }

          // 计算从睡眠开始到这个片段开始的分钟数
          final minutesFromStart =
              segmentStart.difference(startDateTime).inMinutes;

          // 确定阶段类型
          String stage;
          switch (sleepType) {
            case 0:
              stage = 'awake';
              break;
            case 1:
              stage = 'light';
              break;
            case 2:
              stage = 'deep';
              break;
            case 3:
              stage = 'rem';
              break;
            default:
              stage = 'awake';
          }

          sleepData.add({
            'stage': stage,
            'duration': totalTime,
            'startTime': minutesFromStart,
          });
        }
      }
    });

    // 按开始时间排序
    sleepData.sort(
        (a, b) => (a['startTime'] as int).compareTo(b['startTime'] as int));

    // 绘制睡眠阶段数据
    final Paint stagePaint = Paint();

    for (final data in sleepData) {
      final String stage = data['stage'] as String;
      final int duration = data['duration'] as int;
      final int startTime = data['startTime'] as int;

      final Color color = stageColors[stage]!;
      stagePaint.color = color;

      // 计算位置
      final double x = (startTime / totalDuration) * chartWidth;
      final double width = (duration / totalDuration) * chartWidth;

      // 确定Y位置 - 根据睡眠阶段类型（从上到下：清醒、快速眼动、浅睡眠、深睡眠）
      double y;
      switch (stage) {
        case 'awake':
          y = 0; // 顶部
          break;
        case 'rem':
          y = stageHeight; // 第二层
          break;
        case 'light':
          y = stageHeight * 2; // 第三层
          break;
        case 'deep':
          y = stageHeight * 3; // 底部
          break;
        default:
          y = 0;
      }

      // 绘制睡眠阶段块
      final Rect rect = Rect.fromLTWH(x, y, width, stageHeight);
      canvas.drawRect(rect, stagePaint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

/// 构建血氧饱和度图表
Widget _buildBloodOxygenChart(StatusLogic controller) {
  return Obx(() {
    final bloodOxygenData = controller.state.bloodOxygenList;

    if (bloodOxygenData.isEmpty) {
      return Center(
        child: Text(
          '暂无数据',
          style: TextStyle(
            color: Colors.grey[400],
            fontSize: 12.sp,
          ),
        ),
      );
    }

    // 将时间标签转换为小时数（例如 "01:00" -> 1.0）
    List<FlSpot> spots = [];
    for (var point in bloodOxygenData) {
      if (point.value > 0) {
        final timeParts = point.timeLabel.split(':');
        if (timeParts.length == 2) {
          final hour = double.tryParse(timeParts[0]) ?? 0;
          final minute = double.tryParse(timeParts[1]) ?? 0;
          final timeValue = hour + (minute / 60);
          spots.add(FlSpot(timeValue, point.value.toDouble()));
        }
      }
    }

    if (spots.isEmpty) {
      return Center(
        child: Text(
          '暂无有效数据',
          style: TextStyle(
            color: Colors.grey[400],
            fontSize: 12.sp,
          ),
        ),
      );
    }

    // 计算Y轴范围
    final allValues = spots.map((s) => s.y).toList();
    final minValue = allValues.reduce((a, b) => a < b ? a : b);
    final maxValue = allValues.reduce((a, b) => a > b ? a : b);
    final minY = (minValue - 5).clamp(85, 100).toDouble();
    final maxY = (maxValue + 5).clamp(90, 105).toDouble();

    return LineChart(
      LineChartData(
        lineTouchData: const LineTouchData(enabled: false),
        gridData: const FlGridData(show: false),
        titlesData: FlTitlesData(
          show: true,
          leftTitles:
              const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          rightTitles:
              const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          topTitles:
              const AxisTitles(sideTitles: SideTitles(showTitles: false)),
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 18,
              interval: 12,
              getTitlesWidget: (value, meta) {
                if (value == 0 || value == 12 || value == 24) {
                  return Padding(
                    padding: EdgeInsets.only(top: 4.h),
                    child: Text(
                      '${value.toInt()}:00',
                      style: TextStyle(
                        color: const Color(0xFF5A5A5A),
                        fontSize: 8.sp,
                      ),
                    ),
                  );
                }
                return const SizedBox.shrink();
              },
            ),
          ),
        ),
        borderData: FlBorderData(show: false),
        lineBarsData: [
          LineChartBarData(
            spots: spots,
            isCurved: true,
            color: const Color(0xFFFF6B35),
            barWidth: 2,
            dotData: const FlDotData(show: false),
            belowBarData: BarAreaData(
              show: true,
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  const Color(0xFFFF6B35).withOpacity(0.3),
                  const Color(0xFFFF6B35).withOpacity(0.0),
                ],
              ),
            ),
          ),
        ],
        minX: 0,
        maxX: 24,
        minY: minY,
        maxY: maxY,
      ),
    );
  });
}

/// 进度环数据模型
class ProgressRingData {
  final double progress; // 进度值 (0-100)
  final Color color; // 环的颜色

  const ProgressRingData({
    required this.progress,
    required this.color,
  });
}
